package com.zzl.study.auth.security.handler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.server.authorization.oidc.authentication.OidcLogoutAuthenticationToken;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.context.SecurityContextRepository;

import java.io.IOException;

/**
 * @author: zhangzl
 * @date: 2024/6/17 11:42
 * @version: 1.0
 * @description:
 */
public class OidcOAuth2LogoutResponseHandler implements AuthenticationSuccessHandler {

    private final LogoutHandler logoutHandler;

    private final LogoutSuccessHandler logoutSuccessHandler;

    public OidcOAuth2LogoutResponseHandler(SecurityContextRepository securityContextRepository) {
        this.logoutHandler = new OidcOAuth2LogoutHandler(securityContextRepository);
        this.logoutSuccessHandler = new OidcOAuth2LogoutSuccessHandler();
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        OidcLogoutAuthenticationToken oidcLogoutAuthentication = (OidcLogoutAuthenticationToken) authentication;
        this.logoutHandler.logout(request, response, (Authentication) oidcLogoutAuthentication.getPrincipal());
        this.logoutSuccessHandler.onLogoutSuccess(request, response, (Authentication) oidcLogoutAuthentication.getPrincipal());
    }

}
